<template>
	<view class="detail">
		<view class="title">
			{{detailData.title}}
		</view>

		<view class="info">
			<view class="author">
				作者：{{detailData.author}}
			</view>
			<view class="time">
				日期：{{detailData.posttime}}
			</view>
		</view>

		<view class="content">
			<rich-text :nodes="detailData.content"></rich-text>
		</view>
		<view class="description">
			声明
		</view>
	</view>
</template>

<script>
	import {
		parseTime
	} from '@/utils/tool.js'
	export default {
		name: 'detail',
		data() {
			return {
				options: null,
				detailData: {},
			}
		},
		onLoad(res) {
			this.options = res
			this.getDetail()
		},

		methods: {
			getDetail() {
				uni.request({
					url: 'https://ku.qingnian8.com/dataApi/news/detail.php',
					data: this.options,
					success: res => {
						// 将得到的图片动态设置style使其在小程序中大小正常
						res.data.posttime = parseTime(res.data.posttime)
						res.data.content = res.data.content.replace(/<img/gi, '<img style="max-width:100%;"')
						this.detailData = res.data
						this.saveHistory()

						// console.log(this.detailData)
					}
				})
			},
			saveHistory() {
				// 读取缓存是否已经有数据，有就用自己，没有就是空数组
				let historyArr = uni.getStorageSync('historyArr') || []
				// console.log(uni.getStorageSync('historyArr'))
				let item = {
					id: this.detailData.id,
					classid: this.detailData.classid,
					picurl: this.detailData.picurl,
					title: this.detailData.title,
					looktime: parseTime(Date.now())
				}
				
				// 找到当前打开新闻在缓存数组中的索引值
				let index = historyArr.findIndex(each => {
					return each.id == this.detailData.id
				})
				// 找到索引值后判断是否在数组中存在(不存在index为-1)
				if(index>=0){
				// 若存在则删除已存在
					historyArr.splice(index,1)
				}
				// 不存在则直接追加
				// 删除后再追加使其出现在浏览记录的最上面
				historyArr.unshift(item)
				// console.log(item)
				uni.setStorageSync('historyArr', historyArr)
			}
		}
	}
</script>

<style lang="scss">
	.detail {
		padding: 30rpx;

		.title {
			// background-color: skyblue;
			font-size: 46rpx;
			text-align: center;
			margin: 20rpx;
			color: #333;
		}

		.info {
			background-color: #f6f6f6;
			display: flex;
			padding: 10rpx;
			margin: 40rpx 0;
			font-size: 22rpx;
			color: #666;
			justify-content: space-between;

			.author {
				margin-left: 60rpx;
			}
		}

		.content {
			// background-color: grey;
			margin-bottom: 50rpx;
			// H5设置图片不超出最大宽度
			// /deep/ img {
			// 	max-width: 100%;
			// }
		}

		.description {
			background-color: #fef0f0;
			font-size: 26rpx;
			padding: 20rpx;
			color: #f89898;
			line-height: 1.8em;
		}
	}
</style>
